<?php

namespace App\Http\Controllers\API;

use App\On_off;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Server\Basic;

class SwitchController extends Controller
{

    /**
     * 获取对应开关
     *
     * @param $id
     * @return mixed
     */
    public static function getSwitch($id) {
        return On_off::find($id);
    }

    /**
     * 首页获取数据
     * 
     * @return \Illuminate\Http\JsonResponse
     */
    public function index() {
        $switch = On_off::all();
        return self::msgJson('OK', '获取成功', $switch);
    }

    /**
     * 新建
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(Request $request) {
        $info = $request->all();
        if (sizeof($info)) {
            On_off::create($info);
            return self::msgJson('OK', '新建成功');
        }
        return self::msgJson('FAIL', '新建失败');
    }

    /**
     * 修改
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request) {

        $info = $request->all();

        if (!($switch = On_off::find($info['id']))) {
            return self::msgJson('FAIL', '找不到该设备');
        }

        $switch->name = isset($info['name'])?$info['name']:"开关".rand(0,1024);
        $switch->code = $info['code'];
        $switch->save();

        return self::msgJson('OK', '更新成功');
    }

    /**
     * 删除
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request) {

        $id = $request->get('id');

        if (!empty($id)) {
            On_off::destroy($id);
            return self::msgJson('OK', '删除成功');
        }

        return self::msgJson('FALSE', '删除失败');
    }

    /**
     * 下发指令
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function control(Request $request) {

        $id = $request->get('id');

        if (!empty($id)) {

            $control = On_off::find($id);

            $code = $control['code'];

            if (Basic::sendData("CONTROL/:$code", env('TCP_SERVER_HOST'), env('TCP_SERVER_PORT'))) {
                return self::msgJson('OK', '下发命令成功');
            }
        }

        return self::msgJson('FALSE', "下发命令失败");
    }
}
